<template>
  <div class="self_adaption">
    <div class="g-container">
        <p class="main_text">优惠券管理</p>
      <!-- 搜索 -->
      <div class="g-search" ref="searchBox">
        <!-- 信息区域 -->
        <div class="all_select">
          <!-- 时间选择区域 -->
          <span class="demonstration">提交时间：</span>
          <el-date-picker v-model="searchValue.startAt" type="date" placeholder="开始时间" @change="startTime"
            :clearable="false" />
          <span class="demonstration"
            style="display: inline-block; font-size: 12px; color: #898989; margin: 20px">至</span>
          <el-date-picker v-model="searchValue.endAt" type="date" placeholder="结束时间" @change="endTime"
            :clearable="false" />
          &emsp;
          <div style="display: flex; align-items: center">
            <!-- 订单编号 -->
            <div class="input_valye">
              <span class="demonstration">优惠券名称：</span>
              <input type="text" class="input" placeholder="请输入优惠券名称" v-model="searchValue.name" style="width: 175px" />
            </div>
            <!-- 订单状态 -->
            <div class="input_valye">
              <span class="demonstration">优惠券类型：</span><el-select v-model="searchValue.type" class="m-2"
                placeholder="请选择优惠券类型" style="width: 175px">
                <el-option v-for="item in type_options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </div>
          </div>
        </div>
        <!-- 底部按钮区域 -->
        <div class="bottom_btn">
          <el-button class="solid" @click="search">查询</el-button>
          <el-button class="hollow" @click="reset">重置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <div class="cyr-flex">
        <!-- 表格按钮区域 -->
        <div class="mb20">
          <el-button class="hollow" @click="add">添加优惠券</el-button>
          <el-button type="danger" plain>批量删除</el-button>
        </div>

        <div class="cyr-flex-box">
        <!-- 表格区域 -->
        <el-table :data="tableData"  @selection-change="handleSelectionChange"
          :header-cell-style="{ 'text-align': 'center' }" :show-overflow-tooltip="true" v-adaptive border>
          <el-table-column type="selection" width="40" />
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="name" label="优惠券名称" align="center" >
            <template #default="item">
              <el-text tag="span" style="cursor: pointer" @click="look(item.row)">{{ item.row.name }}</el-text>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="优惠券类型" align="center" >
            <template #default="item">
              <div v-if="item.row.type == 0">满减</div>
              <div v-else>折扣</div>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="优惠内容" align="center" >
            <template #default="item">
              <div v-if="item.row.type == 0">满 {{ item.row.limitPrice }} 减 {{ item.row.amount }}</div>
              <div v-else>满 {{ item.row.limitPrice }} 打 {{ item.row.discount }} 折</div>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="剩余数量" align="center" />
          <el-table-column prop="username" label="使用期限" align="center" >
            <template #default="item">
              {{ String(item.row.effectTime).substring(0, 10) }} 至
              {{ String(item.row.expireTime).substring(0, 10) }}
            </template>
          </el-table-column>
          <el-table-column label="操作"  class="operation">
            <template #default="item">
              <div class="table_btn">
                <el-button size="small" class="none" @click="look(item.row)">查看</el-button>
                <el-button size="small" class="none" @click="del(item.row.id)">删除</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="备注" align="center" />
        </el-table>
        <!-- 分页器 -->
        <smartPager v-model:current-page="searchValue.page" v-model:page-size="searchValue.rows" :total="Number(total)"
          @change="pageChange" />
        </div>
      </div>
    </div>
    <!-- 查看订单 -->
    <el-drawer v-model="drawerShow" class="order" size="700px"
      style="position: absolute !important; z-index: 40 !important" :z-index="70" :with-header="false">
      <el-form ref="ruleFormRef" :model="formDataMes" label-width="0px" label-position="right"
        :rules="formDataMes.type == 0 ? rules : rules1">
        <p class="title">添加优惠券</p>
        <p class="mes">基础信息</p>
        <el-form-item prop="name" style="width: 100%">
          <p class="mes_title" style="margin-top: 16px">优惠券名称</p>
          <el-input v-model="formDataMes.name" placeholder="请输入优惠券名称"></el-input>
        </el-form-item>
        <el-form-item prop="type" style="width: 100%">
          <p class="mes_title">优惠券类型</p>
          <el-select v-model="formDataMes.type" class="m-2" placeholder="请选择优惠券类型" @change="typeChange">
            <el-option v-for="item in type_options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="quantity" style="width: 100%">
          <p class="mes_title">发放数量</p>
          <div style="position: relative; width: 100%">
            <el-input v-model="formDataMes.quantity" placeholder="请输入发放数量"></el-input>
            <span style="position: absolute; right: 5px; top: 5px; font-size: 14px; color: #333333">张</span>
          </div>
        </el-form-item>
        <el-form-item prop="rangeDate1" style="width: 100%">
          <p class="mes_title">使用期限</p>
          <div class="range" style="width: 100%">
            <el-radio :checked="true" size="large">日期范围</el-radio>
            <el-date-picker v-model="formDataMes.rangeDate1" type="daterange" range-separator="To"
              start-placeholder="开始时间" end-placeholder="失效时间" size="default" style="flex: 1" @change="timeChange" />
          </div>
        </el-form-item>
        <p class="mes" style="margin-top: 30px">优惠设置</p>
        <!-- /*/*/*/*/*/*/ 满减 /*/*/*/*/*/*/-->
        <div v-if="formDataMes.type == '0'">
          <p class="mes_title" style="margin-top: 16px">满减</p>
          <div class="range" style="width: 100%">
            <el-radio :checked="true" size="large" :disabled="formDataMes.type == '1'">满减优惠</el-radio>
            <span style="display: inline-block; width: 120px; text-align: center">满</span>
            <el-form-item prop="limitPrice1" style="width: 100%; margin-bottom: 0 !important">
              <el-input placeholder="请输入" :disabled="formDataMes.type == '1'"
                v-model="formDataMes.limitPrice1"></el-input>
            </el-form-item>
            <span style="display: inline-block; width: 70px; text-align: center">减</span>
            <el-form-item prop="amount" style="width: 100%; margin-bottom: 0 !important"><el-input placeholder="请输入"
                :disabled="formDataMes.type == '1'" v-model="formDataMes.amount"></el-input></el-form-item>
          </div>
        </div>
        <!-- /*/*/*/*/*/*/ 折扣 /*/*/*/*/*/*/-->
        <div v-else-if="formDataMes.type == '1'">
          <p class="mes_title" style="margin-top: 16px">折扣</p>
          <div class="range sp"
            style="margin-bottom: 70px; align-items: flex-start; display: flex; align-items: center">
            <el-radio :checked="true" size="large" :disabled="formDataMes.type == '0'"
              style="margin-top: 0">折扣</el-radio>
            <span style="display: inline-block; width: 70px; text-align: center">满</span>

            <el-form-item prop="limitPrice2" style="width: 100%; margin-bottom: 0 !important">
              <el-input placeholder="请输入" :disabled="formDataMes.type == '0'"
                v-model="formDataMes.limitPrice2"></el-input>
            </el-form-item>
            <span style="display: inline-block; width: 70px; text-align: center">打</span>

            <el-form-item prop="discount" style="width: 100%; margin-bottom: 0 !important">
              <el-input placeholder="请输入" :disabled="formDataMes.type == '0'" v-model="formDataMes.discount"></el-input>
            </el-form-item>
          </div>
        </div>
        <div v-else
          style="width: 100%; height: 80px; line-height: 80px; color: #b2b2b2; font-size: 14px; text-align: center">
          请先选择优惠券类型
        </div>
      </el-form>
      <div class="btn_center">
        <el-button class="hollow" @click="drawerClose">取消</el-button>
        <el-button class="solid" @click="Sure(ruleFormRef)">确定</el-button>
      </div>
    </el-drawer>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { RequestPreferential, RequestPreferentialGetlistlimit, RequestPreferentialDel } from '@/api/path/index.js';
import moment from 'moment';
import type { FormInstance } from 'element-plus';
import { ElMessage } from 'element-plus';
const ruleFormRef = ref<FormInstance>();
// 弹框数据
const formDataMes = ref({
  name: '',
  type: '0',
  quantity: '',
  effectTime: '',
  expireTime: '',
  limitPrice1: '',
  limitPrice2: '',
  amount: '',
  discount: '',
  rangeDate1: <any>[],
});
// 表单规则
const rules = reactive({
  name: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
  // unit: [{ required: true, message: '请选择商品单位', trigger: 'change' }],
  type: [{ required: true, message: '请选择优惠券类型', trigger: 'blur' }],
  quantity: [
    { required: true, message: '请输入发放数量', trigger: 'blur' },
    {
      pattern: /^\d+(\.\d{1,2})?$/,
      message: '请输入正确数量',
      trigger: 'blur',
    },
  ],
  rangeDate1: [{ required: true, message: '请选择使用时限', trigger: 'blur' }],
  limitPrice1: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    {
      pattern: /^\d+(\.\d{1,2})?$/,
      message: '请输入正确价格，示例20,20.0,20.00',
      trigger: 'blur',
    },
  ],
  amount: [
    { required: true, message: '请输入优惠金额', trigger: 'blur' },
    {
      pattern: /^\d+(\.\d{1,2})?$/,
      message: '请输入正确价格，示例20,20.0,20.00',
      trigger: 'blur',
    },
  ],
});
// 表单规则
const rules1 = reactive({
  name: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
  // unit: [{ required: true, message: '请选择商品单位', trigger: 'change' }],
  type: [{ required: true, message: '请选择优惠券类型', trigger: 'blur' }],
  quantity: [
    { required: true, message: '请输入发放数量', trigger: 'blur' },
    {
      pattern: /^\d+(\.\d{1,2})?$/,
      message: '请输入正确数量',
      trigger: 'blur',
    },
  ],
  rangeDate1: [{ required: true, message: '请选择使用时限', trigger: 'blur' }],
  limitPrice2: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    {
      pattern: /^\d+(\.\d{1,2})?$/,
      message: '请输入正确价格，示例20,20.0,20.00',
      trigger: 'blur',
    },
  ],
  discount: [
    { required: true, message: '请输入折扣', trigger: 'blur' },
    {
      pattern: /^\d+(\.\d{1})?$/,
      message: '请输入正确折扣',
      trigger: 'blur',
    },
  ],
});
const tableData = ref<any>([]); // 表格列表
const total = ref(0); //表格总数
const drawerShow = ref(false); //控制查看订单显示
const order = ref<any>([]); //订单数组
const radio = ref('');
interface RestaurantItem {
  value: string;
  link: string;
}
const consolidateOrder = ref<any>([]);
const restaurants = ref<RestaurantItem[]>([]);
const loadAll = () => {
  return consolidateOrder.value;
};
/**
 * 分页
 */
const pageChange = async (val: number) => {
  searchValue.value.page = val;
  requestPreferentialGetlistlimit();
};
// 挂载
onMounted(() => {
  requestPreferentialGetlistlimit();
  restaurants.value = loadAll();
  handleResize();
  window.addEventListener('resize', handleResize);
});
const searchBox = ref();
const tablelistHeight = ref();
const handleResize = () => {
  const searchBoxHeight = searchBox.value.clientHeight;
  tablelistHeight.value = 110 + searchBoxHeight + 'px';
};

const requestPreferentialGetlistlimit = async () => {
  const a = await RequestPreferentialGetlistlimit(searchValue.value);
  if (a.msg == '操作成功！') {
    tableData.value = a.resultObj.coupons;
    total.value = a.resultObj.count;
  }
};
// 搜索参数
const searchValue = ref({
  type: '',
  name: '',
  startAt: '',
  endAt: '',
  page: 1,
  rows: 10,
});
// 开始时间
const startTime = () => {
  searchValue.value.startAt.setHours(0);
  searchValue.value.startAt.setMinutes(0);
  searchValue.value.startAt.setSeconds(0);
  searchValue.value.startAt = moment(searchValue.value.startAt).format('yyyy-MM-DD HH:mm:ss');
  radio.value = '0';
};
// 结束时间
const endTime = () => {
  searchValue.value.endAt.setHours(23);
  searchValue.value.endAt.setMinutes(59);
  searchValue.value.endAt.setSeconds(59);
  searchValue.value.endAt = moment(searchValue.value.endAt).format('yyyy-MM-DD HH:mm:ss');
  radio.value = '0';
};
/**
 * 类型选择器
 */
const type_options = [
  {
    value: 0,
    label: '满减',
  },
  {
    value: 1,
    label: '折扣',
  },
];
const type = ref('Add'); //Add表示点击的是添加，Edit表示点击编辑
/**
 * 点击添加
 */
const add = () => {
  drawerShow.value = true;
  type.value = 'Add';
};
/**
 * 点击查看
 */
const look = (item: any) => {
  drawerShow.value = true;
  type.value = 'Edit';
  formDataMes.value = {
    name: item.name,
    type: item.type,
    quantity: item.quantity,
    effectTime: item.effectTime,
    expireTime: item.expireTime,
    limitPrice1: item.limitPrice,
    limitPrice2: item.limitPrice,
    amount: item.amount,
    discount: item.discount,
    rangeDate1: [item.effectTime, item.expireTime],
  };
  console.log('查看', formDataMes.value);
};
/**
 * 删除
 */
const del = async (id: number) => {
  const a = await RequestPreferentialDel(id);
  if (a.msg == '操作成功！') {
    ElMessage.success('删除成功');
    requestPreferentialGetlistlimit();
  } else {
    ElMessage.error('删除失败');
  }
};
/**
 * 点击确认
 */

let timer = ref(); //设置记录时间，用于防抖
const Sure = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async (valid: any, fields: any) => {
    if (valid) {
      clearTimeout(timer.value);
      timer.value = setTimeout(async () => {
        if (formDataMes.value.type == '0') {
          const a = await RequestPreferential({
            name: formDataMes.value.name,
            type: formDataMes.value.type,
            quantity: formDataMes.value.quantity,
            effectTime: formDataMes.value.effectTime,
            expireTime: formDataMes.value.expireTime,
            limitPrice: formDataMes.value.limitPrice1,
            amount: formDataMes.value.amount,
          });
          if (a.msg == '操作成功！') {
            ElMessage.success('添加优惠券成功');
            drawerShow.value = false;
            requestPreferentialGetlistlimit();
          } else {
            ElMessage.error('添加优惠券失败！请重试！');
          }
        } else {
          const a = await RequestPreferential({
            name: formDataMes.value.name,
            type: formDataMes.value.type,
            quantity: formDataMes.value.quantity,
            effectTime: formDataMes.value.effectTime,
            expireTime: formDataMes.value.expireTime,
            limitPrice: formDataMes.value.limitPrice2,
            discount: formDataMes.value.discount,
          });
          if (a.msg == '操作成功！') {
            ElMessage.success('添加优惠券成功');
            drawerShow.value = false;
          } else {
            ElMessage.error('添加优惠券失败！请重试！');
          }
        }
      }, 500);
    }
  });
};
/**
 * 搜索
 */
const search = async () => {
  if (moment(searchValue.value.startAt).diff(moment().format('YYYY-MM-DD HH:mm:ss')) >= 0) {
    ElMessage.error('开始时间不能晚于当前日期');
  } else {
    if (searchValue.value.startAt !== '' && searchValue.value.endAt !== '') {
      if (moment(searchValue.value.startAt).diff(moment(searchValue.value.endAt)) <= 0) {
        searchValue.value.page = 1;
        requestPreferentialGetlistlimit();
      } else {
        ElMessage.error('结束时间不能早于开始时间');
      }
    } else {
      searchValue.value.page = 1;
      requestPreferentialGetlistlimit();
    }
  }
};
/**
 * 点击重置
 */
const reset = () => {
  searchValue.value = {
    type: '',
    name: '',
    startAt: '',
    endAt: '',
    page: 1,
    rows: 10,
  };
  requestPreferentialGetlistlimit();
  radio.value = '0';
};
/**
 * 表格复选框选中事件
 */
const handleSelectionChange = (selection: any) => {
  order.value = [];
  for (let x = 0; x < tableData.value.length; x++) {
    tableData.value[x].selection = false;
  }
  for (let i = 0; i < selection.length; i++) {
    selection[i].selection = true;
    order.value.push(selection[i]);
  }
};
/**
 * 时间改变
 */
const timeChange = () => {
  formDataMes.value.effectTime = formDataMes.value.rangeDate1[0];
  formDataMes.value.effectTime.setHours(0);
  formDataMes.value.effectTime.setMinutes(0);
  formDataMes.value.effectTime.setSeconds(0);
  formDataMes.value.effectTime = moment(formDataMes.value.effectTime).format('yyyy-MM-DD HH:mm:ss');

  // 过期时间
  formDataMes.value.expireTime = formDataMes.value.rangeDate1[1];
  formDataMes.value.expireTime.setHours(23);
  formDataMes.value.expireTime.setMinutes(59);
  formDataMes.value.expireTime.setSeconds(59);
  formDataMes.value.expireTime = moment(formDataMes.value.expireTime).format('yyyy-MM-DD HH:mm:ss');
};
/**
 * 折扣类型改变
 */
const typeChange = () => {
  if (formDataMes.value.type == '0') {
    formDataMes.value.limitPrice1 = '';
    formDataMes.value.limitPrice2 = '';
    formDataMes.value.amount = '';
    formDataMes.value.discount = '';
  } else {
    formDataMes.value.limitPrice1 = '';
    formDataMes.value.limitPrice2 = '';
    formDataMes.value.amount = '';
    formDataMes.value.discount = '';
  }
};
/**
 * 抽屉关闭
 */
const drawerClose = () => {
  drawerShow.value = false
};
</script>
<style lang="scss" scoped>
@import '@/assets/css/plateform/Article/Content.css';
@import '@/assets/css/plateform/Shop/GoodsManage.css';

.g-container{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.order {
  .title {
    font-size: 18px;
    margin-top: 10px;
    margin-bottom: 20px;
    font-weight: bold;
  }

  .mes {
    font-size: 16px;
    line-height: 40px;
    color: #1d2129;
    background: #f5f7fa;
    padding-left: 10px;
  }

  .mes_title {
    font-size: 14px;
    color: #333;
    line-height: 22px;
    margin-bottom: 8px;
  }

  .range {
    display: flex;
    align-items: center;
    position: relative;

    .range_box {
      display: flex;
      align-items: center;
      width: calc(100% - 110px);

      .range_box1 {
        width: 100%;
        margin-top: 20px;
      }
    }

    .range_operat {
      width: 64px;
      display: flex;
      align-items: center;
      position: absolute;
      right: 0;
      bottom: 5px;
    }
  }
}

::v-deep .el-radio.el-radio--large {
  width: 78px !important;
}

.sp ::v-deep .el-radio.el-radio--large {
  margin-top: 15px;
}

::v-deep .el-drawer__body {
  padding: 20px !important;
  background: #fff;
}

.table {
  //height: calc(100% - v-bind(tablelistHeight)) !important;
}

::v-deep .el-table--fit {
  //height: calc(100% - 120px) !important;
}

.table :deep(.el-table__cell) {
  text-align: center;
}

::v-deep .el-radio-group {
  width: 100% !important;
  background: pink !important;
}

::deep(.el-radio-group) {
  width: 100% !important;
  background: pink !important;
}

::v-deep .el-range-editor--small.el-input__wrapper {
  height: 40px !important;
}

.el-form-item :deep(.el-input-group__prepend) {
  width: 10px;
  background-color: #116cf8;
  color: #fff;
}

.el-form-item :deep(.el-upload--picture-card) {
  height: 100px;
  width: 100px;
  opacity: 0;
}

.btn {
  width: 150px;
  position: absolute;
  right: 20px;
  bottom: 40px;
}

::v-deep .el-drawer.rtl {
  background: #f5f9ff !important;
  width: 750px !important;
}

.close_order :deep(.is-finish .el-step__line) {
  background: #f57373;
}

.order_edit {
  position: fixed;
  width: 40%;
  height: 50%;
  background: #fff;
  z-index: 300;
  top: 25%;
  left: 25%;
  overflow: scroll;

  .el-form {
    position: relative;
    z-index: 350;
    padding: 20px 50px;

    .el-form-item {
      position: relative;
      z-index: 400;

      .el-input {
        position: relative;
        z-index: 700;
      }
    }
  }
}

.el-table .warning-row {
  background: #44a2ff !important;
}

::v-deep .el-table--enable-row-transition .el-table__body td.el-table__cell {
  z-index: initial !important;
}
</style>
